package com.yl.utils.speechToText;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nls.client.AccessToken;
import com.yl.utils.HttpUtil;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 阿里云 录音文件极速版util
 *
 * @param
 * @date 2023/10/7 16:37
 **/
public class SpeechFlashRecognizerDemo {
    private String appkey;
    private StringBuilder builder = new StringBuilder("");

    public SpeechFlashRecognizerDemo(String appkey) {
        this.appkey = appkey;
    }

    public String process(String fileName, String token, String format, int sampleRate) {
        /**
         * 设置HTTPS REST POST请求
         * 1.使用http协议
         * 2.语音识别服务域名：nls-gateway.cn-shanghai.aliyuncs.com
         * 3.语音识别接口请求路径：/stream/v1/FlashRecognizer
         * 4.设置必须请求参数：appkey、token、format、sample_rate
         */
        String url = "https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/FlashRecognizer";
        String request = url;
        request = request + "?appkey=" + appkey;
        request = request + "&token=" + token;
        request = request + "&format=" + format;
        request = request + "&sample_rate=" + sampleRate;
        System.out.println("Request: " + request);
        /**
         * 设置HTTPS头部字段
         *
         * 1.Content-Type：application/octet-stream
         */
        HashMap<String, String> headers = new HashMap<String, String>();
        /**
         * 发送HTTPS POST请求，返回服务端的响应。
         */
        long start = System.currentTimeMillis();
        String response;
        if (new File(fileName).isFile()) {
            headers.put("Content-Type", "application/octet-stream");
            response = HttpUtil.sendPostFile(request, headers, fileName);
        } else {
            headers.put("Content-Type", "application/text");
            response = HttpUtil.sendPostLink(request, headers, fileName);
        }
        System.out.println("latency = " + (System.currentTimeMillis() - start) + " ms");
        if (response != null) {
            StringBuilder builder = new StringBuilder();
            // 处理数据
            JSONObject parseObject = JSONObject.parseObject(response);
            if (parseObject.containsKey("flash_result")) {
                Map<String, Object> map = (Map<String, Object>) parseObject.get("flash_result");
                if (map.containsKey("sentences")) {
                    List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("sentences");
                    if (list != null && list.size() != 0) {
                        list.stream().forEach(resultMap -> {
                            builder.append(resultMap.get("text"));
                        });
                    }
                }
            }
            System.out.println("Response: " + response);
            return builder.toString();
        } else {
            System.err.println("识别失败!");
        }
        return "";
    }

    public static void main(String[] args) {
        AccessToken accessToken = new AccessToken("LTAI5tFg34gxhYnD3W1XnHFG", "xaAifNXC6gESmF9ruf9YooxIb1ASDE");
        try {
            accessToken.apply();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String token = accessToken.getToken();
        long expireTime = accessToken.getExpireTime();
        SpeechFlashRecognizerDemo demo = new SpeechFlashRecognizerDemo("eLGdmI5lO8FHIMsj");
        //String fileName = SpeechRecognizerRestfulDemo.class.getClassLoader().getResource("./nls-sample-16k.wav").getPath();
        // 重要：此处用一个本地文件来模拟发送实时流数据，实际使用时，您可以从某处实时采集或接收语音流并发送到ASR服务端。
//        String fileName = "https://gw.alipayobjects.com/os/bmw-prod/0574ee2e-f494-45a5-820f-63aee583045a.wav";
        String fileName = "D:\\456.wav";
        //fileName="./nls-sample-16k.wav";
        String format = "wav";
        int sampleRate = 16000;

        String process = demo.process(fileName, token, format, sampleRate);
        System.out.println("获取到的最后的结果是" + process);
        System.exit(-1);
    }
}
